<template>
  <div class="tab-page-main">
    <el-tabs v-model="other.tabActive" type="card" class="page-tabs">
      <el-tab-pane label="代理列表" :name="0">
        <div class="tab-page-content">
          <div class="form pt-[15px]">
            <el-form>
              <el-row :gutter="12">
                <el-col :span="3">
                  <el-form-item>
                    <el-input v-model="form.nickname" placeholder="用户名/昵称/备注" />
                  </el-form-item>
                </el-col>
                <el-col :span="21">
                  <el-button type="primary" @click.stop="search">搜索</el-button>
                  <el-button type="danger" @click.stop="handleRefresh">清空</el-button>
                  <el-button v-if="route.query.id" type="success" @click="goBack">返回</el-button>
                </el-col>
              </el-row>
            </el-form>
          </div>
          <div class="grow-[1] h-0">
            <el-table
              scrollbar-always-on
              v-loading="state.loading"
              :data="list"
              height="100%"
              border
              stripe
              fit
            >
              <template #empty>
                <ui-empty />
              </template>
              <el-table-column prop="Avatar" align="center" label="头像" width="60">
                <template #default="{ row }: TableItem">
                  <div class="flex items-center justify-center">
                    <avatar :size="30" :src="row.Avatar" />
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="Name" label="用户名" align="center" show-overflow-tooltip>
                <template #default="{ row }: TableItem">
                  {{ row.Name || "--" }}
                </template>
              </el-table-column>
              <el-table-column prop="Nickname" label="昵称" align="center" show-overflow-tooltip>
                <template #default="{ row }: TableItem">
                  {{ row.Nickname || "--" }}
                </template>
              </el-table-column>
              <el-table-column
                prop="Note"
                label="代理备注"
                align="center"
                show-overflow-tooltip
                min-width="100"
              >
                <template #default="{ row }: TableItem">
                  {{ row.Note || "--" }}
                </template>
              </el-table-column>
              <el-table-column prop="Level" label="会员等级" align="center" width="100">
                <template #default="{ row }: TableItem">
                  {{ row.Level || "--" }}
                </template>
              </el-table-column>
              <el-table-column prop="AgentCount" align="center" label="下级代理人数" width="120">
                <template #default="{ row }: TableItem">
                  <template v-if="row.AgentCount == 0">
                    {{ row.AgentCount }}
                  </template>
                  <el-button v-else type="primary" size="small" @click="toSubAgent(row)">
                    {{ row.AgentCount }}
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column prop="UserCount" align="center" label="下线人数" min-width="100">
                <template #default="{ row }: TableItem">
                  <template v-if="row.UserCount == 0">
                    {{ row.UserCount }}
                  </template>
                  <el-button v-else type="primary" size="small" @click="openSubListDialog(row)">
                    {{ row.UserCount }}
                  </el-button>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="320" align="center">
                <template #default="{ row }: TableItem">
                  <el-button type="primary" size="small" @click="addAgent(row)">
                    添加{{ toChinesNum(row.Level + 1) }}级代理
                  </el-button>
                  <el-button type="success" size="small" @click="addSub(row)"> 添加下线 </el-button>
                  <el-button type="danger" size="small" @click="cancelAgent(row)">
                    取消代理
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="flex justify-end my-[10px] mx-[15px]">
            <ui-pagination
              :total="state.total"
              v-model:pageSize="state.pageSize"
              v-model:currentPage="state.page"
              @current-change="getData"
            ></ui-pagination>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="代理返佣" :name="1">
        <div class="tab-page-content">
          <AgentRebate />
        </div>
      </el-tab-pane>
      <el-tab-pane label="佣金报表" :name="2">
        <div class="tab-page-content">
          <Rebate />
        </div>
      </el-tab-pane>
    </el-tabs>
    <add-agent-dialog
      :level="toChinesNum((currentData?.Level || 0) + 1)"
      :pid="currentData?.UserId || null"
      ref="addAgentDialogRef"
      @update="getData"
    />
    <add-agentsub-dialog
      ref="addAgentSubDialogRef"
      :pid="currentData?.UserId || null"
      @update="getData"
    />
    <agentsub-list-dialog
      ref="agentsubListDialogRef"
      :name="currentData?.Nickname || currentData?.Name || ''"
      :pid="currentData?.UserId || null"
      @update="getData"
    />
  </div>
</template>
<script setup lang="ts">
import AddAgentDialog from "./components/add-agent-dialog.vue";
import AddAgentsubDialog from "./components/add-agentsub-dialog.vue";
import AgentsubListDialog from "./components/agentsub-list-dialog.vue";
import AgentRebate from "../report/components/agent-rebate.vue";
import Rebate from "../report/components/rebate.vue";

import { cloneDeep } from "lodash-es";
import { useList } from "@/hooks/useList";
import { reqAgentList, reqDelAgent } from "@/api/user";
import { ElMessageBox } from "element-plus";
import { toChinesNum } from "@/utils/common";
import { message } from "@/utils/message";

interface Params {
  Nickname?: string;
  ParentId?: string;
}

interface TableItem {
  row: AgentMo;
}
const other = reactive({
  loading: false,
  tabActive: 0
});
const router = useRouter();
const route = useRoute();
const form = reactive<{
  nickname: string;
}>({
  nickname: ""
});
const currentData = ref<AgentMo | null>(null);
const addAgentDialogRef = ref();
const addAgentSubDialogRef = ref();
const agentsubListDialogRef = ref();

// 获取参数
const getParams = () => {
  const params: Params = {};
  if (form.nickname) {
    params.Nickname = form.nickname;
  }
  if (route.query.id && !isNaN(Number(route.query.id as string))) {
    params.ParentId = route.query.id as string;
  }

  return params;
};
const { state, list, search, getData } = useList<AgentMo, Params>(reqAgentList, getParams);

// 重置
const handleRefresh = () => {
  form.nickname = "";
  search();
};

// 跳转下级代理
const toSubAgent = (row: AgentMo) => {
  nextTick(() => {
    router.push({
      path: "/admin/user/agent",
      query: {
        id: row.UserId,
        level: row.Level
      }
    });
  });
};

// 打开下线列表
const openSubListDialog = (row: AgentMo) => {
  currentData.value = cloneDeep(row);
  nextTick(() => {
    agentsubListDialogRef.value?.open();
  });
};

// 添加下级代理
const addAgent = (row: AgentMo) => {
  currentData.value = cloneDeep(row);
  nextTick(() => {
    addAgentDialogRef.value?.open();
  });
};

// 添加下线
const addSub = (row: any) => {
  currentData.value = cloneDeep(row);
  nextTick(() => {
    addAgentSubDialogRef.value?.open();
  });
};

// 取消代理
const cancelAgent = (row: AgentMo) => {
  ElMessageBox.confirm(`是否进行【取消代理】操作`, "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    distinguishCancelAndClose: true,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true; // 设置 "确定" 按钮加载中
          await reqDelAgent(row.UserId);
          instance.confirmButtonLoading = false;
          message.success("取消代理成功");
          getData();
          done(); // 操作成功后关闭对话框
        } catch (error) {
          done();
          console.error("操作失败", error);
          instance.confirmButtonLoading = false; // 如果失败，取消加载状态
        }
      } else {
        done(); // 取消时直接关闭
      }
    }
  });
};

const goBack = () => {
  router.back();
};

watch(
  () => route.query.id,
  () => {
    getData();
  }
);

onMounted(() => {
  getData();
});
</script>
<style lang="scss" scoped>
:deep() {
  .el-tabs--card {
    .el-tabs__header {
      .el-tabs__item {
        font-size: 15px !important;
      }
      .el-tabs__item.is-active {
        font-weight: normal !important;
      }
    }
  }
}
</style>
